#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <inttypes.h>

#define PORT 8080
#define BUFFER_SIZE 4096

// 反序列化字符串
int deserialize_string(const uint8_t* buffer, char* str, size_t str_size) {
    uint32_t net_len;
    memcpy(&net_len, buffer, sizeof(net_len));
    size_t len = ntohl(net_len);
    
    if (len >= str_size) {
        return -1; // 字符串缓冲区太小
    }
    
    memcpy(str, buffer + sizeof(net_len), len);
    str[len] = '\0';
    
    return sizeof(net_len) + len;
}

// 处理客户端请求
void handle_client(int client_sock) {
    uint8_t buffer[BUFFER_SIZE];
    int bytes_read = recv(client_sock, buffer, BUFFER_SIZE, 0);
    
    if (bytes_read <= 0) {
        perror("接收请求失败");
        return;
    }
    
    char filename[256];
    int offset = deserialize_string(buffer, filename, sizeof(filename));
    
    if (offset < 0) {
        printf("文件名反序列化失败\n");
        return;
    }
    
    // 解析偏移量
    uint64_t net_file_offset;
    memcpy(&net_file_offset, buffer + offset, sizeof(net_file_offset));
    uint64_t file_offset = be64toh(net_file_offset);
    offset += sizeof(net_file_offset);
    
    // 解析块大小
    uint64_t net_chunk_size;
    memcpy(&net_chunk_size, buffer + offset, sizeof(net_chunk_size));
    uint64_t chunk_size = be64toh(net_chunk_size);
    
    printf("收到文件块请求: %s (偏移: %" PRIu64 ", 大小: %" PRIu64 ")\n", 
           filename, file_offset, chunk_size);
    
    // 检查文件是否存在
    struct stat st;
    if (stat(filename, &st) != 0) {
        printf("文件不存在: %s\n", filename);
        // 发送错误响应（这里简化处理，直接关闭连接）
        return;
    }
    
    // 检查偏移量是否有效
    if (file_offset >= st.st_size) {
        printf("偏移量超出文件范围: %" PRIu64 " >= %ld\n", file_offset, st.st_size);
        // 发送空响应
        uint64_t net_offset = htobe64(file_offset);
        uint64_t net_size = htobe64(0);
        send(client_sock, &net_offset, sizeof(net_offset), 0);
        send(client_sock, &net_size, sizeof(net_size), 0);
        return;
    }
    
    // 计算实际可读取的大小
    uint64_t actual_chunk_size = chunk_size;
    if (file_offset + chunk_size > st.st_size) {
        actual_chunk_size = st.st_size - file_offset;
    }
    
    // 打开文件
    FILE* file = fopen(filename, "rb");
    if (!file) {
        perror("打开文件失败");
        return;
    }
    
    // 定位到指定偏移量
    if (fseek(file, file_offset, SEEK_SET) != 0) {
        perror("文件定位失败");
        fclose(file);
        return;
    }
    
    // 发送响应头（偏移量和块大小）
    uint64_t net_offset = htobe64(file_offset);
    uint64_t net_size = htobe64(actual_chunk_size);
    
    if (send(client_sock, &net_offset, sizeof(net_offset), 0) < 0 ||
        send(client_sock, &net_size, sizeof(net_size), 0) < 0) {
        perror("发送响应头失败");
        fclose(file);
        return;
    }
    
    printf("发送文件块: 偏移量 %" PRIu64 ", 大小 %" PRIu64 "\n", file_offset, actual_chunk_size);
    
    // 发送文件内容
    size_t bytes_sent_total = 0;
    while (bytes_sent_total < actual_chunk_size) {
        size_t to_read = actual_chunk_size - bytes_sent_total;
        if (to_read > BUFFER_SIZE) {
            to_read = BUFFER_SIZE;
        }
        
        size_t bytes_read = fread(buffer, 1, to_read, file);
        if (bytes_read == 0) {
            break; // 读取结束或出错
        }
        
        if (send(client_sock, buffer, bytes_read, 0) < 0) {
            perror("发送文件内容失败");
            break;
        }
        
        bytes_sent_total += bytes_read;
        
        // 显示进度
        int progress = (int)((double)bytes_sent_total / actual_chunk_size * 100);
        printf("\r发送进度: %d%%", progress);
        fflush(stdout);
    }
    
    printf("\n文件块发送完成\n");
    fclose(file);
}

int main() {
    int server_fd, client_sock;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    
    // 创建套接字
    if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
        perror("socket failed");
        exit(EXIT_FAILURE);
    }
    
    // 设置套接字选项
    if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
        perror("setsockopt");
        exit(EXIT_FAILURE);
    }
    
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons(PORT);
    
    // 绑定套接字
    if (bind(server_fd, (struct sockaddr*)&address, sizeof(address)) < 0) {
        perror("bind failed");
        exit(EXIT_FAILURE);
    }
    
    // 监听
    if (listen(server_fd, 3) < 0) {
        perror("listen");
        exit(EXIT_FAILURE);
    }
    
    printf("文件块服务器启动，监听端口 %d\n", PORT);
    
    while (1) {
        // 接受连接
        if ((client_sock = accept(server_fd, (struct sockaddr*)&address, (socklen_t*)&addrlen)) < 0) {
            perror("accept");
            continue;
        }
        
        printf("客户端连接成功\n");
        
        // 处理客户端请求
        handle_client(client_sock);
        
        close(client_sock);
        printf("客户端连接关闭\n");
    }
    
    return 0;
}